import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/record/items/data_left_list.dart';
import 'package:sports_new/widgets/base/qkd_dialog.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../controller/record/player_logic.dart';
import '../../resources/colours.dart';
import '../../resources/styles.dart';
import '../../utils/utils.dart';
import '../../widgets/base/qkd_text.dart';
import '../../widgets/loading/no_data_widget.dart';

class PlayerPage extends StatefulWidget {
  const PlayerPage(this.leagueId, {super.key, required this.tag});

  final int leagueId;
  final String tag;

  @override
  State<PlayerPage> createState() => _PlayerPageState();
}

class _PlayerPageState extends State<PlayerPage>
    with AutomaticKeepAliveClientMixin {
  late PlayerLogic logic;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<PlayerLogic>(
      tag: widget.tag,
      initState: (state) {
        logic = Get.put(
          PlayerLogic(widget.leagueId, widget.tag), tag: widget.tag
        );
      },
      builder: (_) {
        return VisibilityDetector(
          key: Key(widget.tag),
          onVisibilityChanged: (VisibilityInfo info) {
            logic.visible = !info.visibleBounds.isEmpty;
          },
          child: LoadingWidget<bool>(
            isLoading: logic.struct == null,
            data: logic.struct?.length == 0,
            child: () => Row(
              children: [
                DataLeftList(
                  logic.struct!.map((e) => e.value!).toList(),
                  logic.structIndex, ((p0) {
                    Utils.onEvent('zqsjpd_qyb',
                        params: {'zqsjpd_qyb': logic.struct![p0]});
                    logic.onSelectLeft(p0);
                  })
                ),
                right(),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget right() {
    return Expanded(
      child: Container(
        color: Colours.white,
        child: Padding(
          padding: const EdgeInsets.only(left: 10, right: 4),
          child: LoadingWidget<bool>(
            isLoading: logic.header == null,
            data: logic.header?.length == 0,
            noData: const NoDataWidget(needScroll: true),
            child: () => Column(
              children: [
                header(),
                Expanded(
                  child: EasyRefresh(
                    onRefresh: () async => logic.getData(),
                    controller: logic.refreshController,
                    child: LoadingWidget<int>(
                      isLoading: false,
                      data: logic.playerAll?.length,
                      noData: const NoDataWidget(needScroll: true),
                      child: () => MediaQuery.removePadding(
                        context: context,
                        removeTop: true,
                        child: ListView.builder(
                          itemBuilder: (context, index) => playerWidget(index),
                          itemCount: logic.playerAll?.length ?? 0,
                        )
                      )
                    )
                  )
                )
              ]
            )
          )
        ),
      )
    );
  }

  header() {
    return SizedBox(
      height: 38,
      child: Row(
        children: [
          QkdText(
            '球员',
            textAlign: TextAlign.center,
            color: Colours.grey66, fontSize: 13
          ).sized(width: 34),
          const Spacer(),
          if(logic.channel.recordType == 0)
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              QkdText(
                logic.header?.last ?? "",
                textAlign: TextAlign.center,
                color: Colours.grey66, fontSize: 13
              ),
            ],
          ).sized(width: 70).tap(
            () => Get.dialog(QkdDialog.single('进球数包含点球'))
          ),
          if(logic.channel.recordType == 1)
          ...logic.header!.map(
            (e) => SizedBox(
              width: e == '球队' ?60:42,
              child: QkdText(
                e,
                textAlign: TextAlign.center,
                color: Colours.grey99, fontSize: 13,
              )
            )
          ),
        ],
      ),
    );
  }

  Widget playerWidget(int index) {
    final data = logic.playerAll![index];
    return SizedBox(
        height: 50,
        child: Row(children: [
          QkdText(
            data.index ?? '',
            textAlign: TextAlign.center,
            fontSize: 13
          ).sized(width: 34),
          Stack(
            clipBehavior: Clip.none,
            children: [
              CachedNetworkImage(
                height: 32, width: 24,
                fit: BoxFit.cover,
                imageUrl: data.playerLogo!,
                placeholder: (context, url) => Styles.placeholderIcon(),
                errorWidget: (context, url, error) => Image.asset(
                  Utils.getImgPath('zq_placeholder.png'),
                  height: 32, width: 24
                )
              ),
              if(logic.channel.recordType == 0)
              Positioned(
                bottom: -4, right: -4,
                child: CachedNetworkImage(
                  width: 16, height: 16,
                  fit: BoxFit.cover,
                  imageUrl: data.teamLogo ?? "",
                  placeholder: (context, url) => Styles.placeholderIcon(),
                  errorWidget: (context, url, error) => Image.asset(
                    Utils.getImgPath('zq_placeholder.png'),
                    height: 16,
                    width: 16,
                  )
                )
              )
            ]
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                QkdText(
                  data.playerName ?? '',
                  fontSize: 13,
                  maxLines: 1,
                ),
                const SizedBox(height: 2),
                QkdText(
                  logic.channel.recordType == 0?
                  '${data.playerPosition} ${data.teamName}':
                  '${data.playerPoints}分 ${data.playerRebounds}板 ${data.playerAssists}助',
                  color: Colours.grey66, fontSize: 11,
                  maxLines: 1,
                )
              ],
            ),
          ),
          if(logic.channel.recordType == 1)
          ...List.generate(
            data.values!.length,
            (index) => SizedBox(
              width: logic.header![index] == '球队'?60:42,
              child: QkdText(
                data.values![index],
                textAlign: TextAlign.center,
                fontSize: 13
              )
            )
          ),
          if(logic.channel.recordType == 0)
          QkdText(
            data.values?.last ?? '',
            textAlign: TextAlign.center,
            fontSize: 13,
          ).sized(width: 70)
        ])
    );
  }

  @override
  bool get wantKeepAlive => true;
}
